package com.uphone.kingmall.fragment.order;

import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.google.zxing.WriterException;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uphone.kingmall.activity.order.AllOrderActivity;
import com.uphone.kingmall.activity.order.ApplyForRefundActivity;
import com.uphone.kingmall.activity.order.OrderCodeActivity;
import com.uphone.kingmall.activity.order.OrderDetailActivity;
import com.uphone.kingmall.activity.order.OrderFollowActivity;
import com.uphone.kingmall.adapter.RvOrderAdapter;
import com.uphone.kingmall.base.BaseFragment;
import com.uphone.kingmall.bean.OrderBean;
import com.uphone.kingmall.listener.NetListCallBack;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.DensityUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.QRCodeUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;
import com.uphone.kingmall.view.dialog.RadishDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
//import io.rong.imkit.RongIM;
//import io.rong.imlib.model.CSCustomServiceInfo;

/**
 * <pre>
 *     author : 孙增艳
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2019/2/25
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class WaitTakeGoodsFragment extends BaseFragment {

    public static WaitTakeGoodsFragment fragment;
    @BindView(R.id.rv_wait)
    RecyclerView rvWait;
    @BindView(R.id.srl_wait)
    SmartRefreshLayout srlWait;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    int page = 1;
    private List<OrderBean.DataBean> orderBeanList = new ArrayList<>();
    private RvOrderAdapter orderAdapter;

    public static WaitTakeGoodsFragment newInstance() {
        synchronized (WaitTakeGoodsFragment.class) {
            if (fragment == null) {
                fragment = new WaitTakeGoodsFragment();
            }
        }
        return fragment;
    }

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_fragment_wait_take_goods;
    }

    @Override
    public void initData() {
    }

    @Override
    public void loadJPush() {
        super.loadJPush();
        loadData(1);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(1);
    }


    private void loadData(int page) {
        this.page = page;
        HttpParams params = new HttpParams();
        params.put("page", page);
        params.put("limit", "10");
        params.put("orderState", "30");
        CommonUtil.netRv(new OrderBean(), orderAdapter, orderBeanList, MyUrl.getUserOrders, params, page, new NetListCallBack<OrderBean.DataBean>() {
            @Override
            public void callBack(List<OrderBean.DataBean> list) {
                orderBeanList = list;


                if (tvEmpty != null) {
                    if (orderBeanList == null || orderBeanList.size() == 0) {
                        tvEmpty.setVisibility(View.VISIBLE);
                    } else {
                        tvEmpty.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void initView(View view) {
        //设置是否打开自动加载更多
        srlWait.setEnableAutoLoadMore(false);
        //取消内容不满一页时开启上拉加载功能
        srlWait.setEnableLoadMoreWhenContentNotFull(false);

        srlWait.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                loadData(1);
            }
        });
        srlWait.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                loadData(++page);
            }
        });
        //代码设置刷新加载样式
        srlWait.setPrimaryColorsId(R.color.colorBg, R.color.black);//全局设置主题颜色
        srlWait.setRefreshHeader(new ClassicsHeader(getContext()));
        srlWait.setRefreshFooter(new BallPulseFooter(getContext()).setSpinnerStyle(SpinnerStyle.Scale));

        orderAdapter = new RvOrderAdapter(getContext(), OrderBean.DSH, orderBeanList, new RvOrderAdapter.OnShareClickListener() {
            @Override
            public void onShareClickListener(int shopPosition, int goodsPosition) {
                OrderBean.DataBean.GoodslistBean goodsBean = orderBeanList.get(shopPosition).getGoodslist().get(goodsPosition);
                DialogUtil.showShareDailog(getActivity(), goodsBean.getGoodsName() + "", MyUrl.h5GoodDetail + goodsBean.getGoodsId(), goodsBean.getGoodsName() + "");
            }
        });
        rvWait.setLayoutManager(new LinearLayoutManager(getContext()));
        rvWait.setAdapter(orderAdapter);
        orderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_lxsj2://联系商家
                    case R.id.tv_lxsj3://联系商家
//                        if (orderBeanList.get(position) != null && !TextUtils.isEmpty(orderBeanList.get(position).getShopPhone())) {
//                            DialogUtil.showCallDialog(getActivity(), orderBeanList.get(position).getShopPhone());
//                        } else {
//                            //联系商家
//                            CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                            final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                            RongIM.getInstance().startCustomerServiceChat(getActivity(), ConstansUtils.CSCustomServiceId, "", csInfo);
//                        }
                        break;
                    case R.id.tv_sqtk2://申请退款
                    case R.id.tv_sqtk3://申请退款
                        IntentUtils.getInstance().with(getActivity(), ApplyForRefundActivity.class)
                                .putSerializable(ConstansUtils.BEAN, orderBeanList.get(position))
                                .putInt(ConstansUtils.TYPE, 2).start();
                        break;
                    case R.id.tv_ckwl://查看物流
                        CommonUtil.startIntent(getActivity(), OrderFollowActivity.class, orderBeanList.get(position).getOrderId());
                        break;
                    case R.id.tv_qrsh://确认收货
                        showDialog(MyUrl.receiveOrder, "确认收货", orderBeanList.get(position).getOrderId());
                        break;
                    case R.id.tv_xfm://消费码
//                        showqr(orderBeanList.get(position));

                        IntentUtils.getInstance().with(getActivity(), OrderCodeActivity.class)
                                .putString("checkCode", orderBeanList.get(position).getCheckCode()).start();
                        break;
                    default:
                        break;
                }
            }
        });

        orderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CommonUtil.startIntent(getActivity(), OrderDetailActivity.class, orderBeanList.get(position).getOrderId());
            }
        });
    }

    private void showDialog(final String url, final String msg, final int orderId) {
        CommonUtil.showAlterDialog(getActivity(), msg + "?", new CommonUtil.OnAlterDialogCallBack() {
            @Override
            public void callBack(RadishDialog dialog, View view) {
                loadNet(url, msg, orderId);
            }
        });
    }

    private void loadNet(String url, final String msg, int id) {
        HttpParams params = new HttpParams();
        params.put("orderId", id);
        OkGoUtils.normalRequest(url, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    ToastUtils.showShortToast(getActivity(), msg + "成功");
                    if (getActivity() instanceof AllOrderActivity) {
                        ((AllOrderActivity) getActivity()).setCurrentItem(0);
                    }
                    loadData(1);
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void showqr(OrderBean.DataBean orderBean) {
        View dialogView = View.inflate(getActivity(), R.layout.kingmall_dialog_qrcode, null);
        ImageView iv_qrcode = dialogView.findViewById(R.id.iv_qrcode);
        //绘制二维码
        try {
            Bitmap bitmap = QRCodeUtils.createQRCode
                    (ConstansUtils.QRCodeOrderCheck + orderBean.getCheckCode() + "", DensityUtil.dip2px(getActivity(), 260));
            iv_qrcode.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        new RadishDialog.Builder(getActivity()).setView(dialogView)
                .show();
    }

}
